package com.ruoyi.common.core.exception;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.BizCodeEnum;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "com.ruoyi.mall.product.controller")
public class ExceptionControllerAdvice {


    /**
     * 处理验证异常的方法
     *
     * @param e e
     * @return R
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<Map<String, String>> handlerValidException(MethodArgumentNotValidException e) {
        Map<String, String> map = new HashMap<>(8);
        e.getFieldErrors().forEach(fieldError -> map.put(fieldError.getField(), fieldError.getDefaultMessage()));
        return R.fail(map, BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg());
    }

    /**
     * 系统的其他异常
     *
     * @param throwable throwable
     * @return R
     */
    @ExceptionHandler(Throwable.class)
    public R<String> handlerException(Throwable throwable) {
        System.out.println("错误信息" + throwable);
        return R.fail(throwable.getMessage(), BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
